//
//  ViewController.swift
//  UI03-Greeting
//
//  Created by yao_yu on 14-8-21.
//  Copyright (c) 2014年 yao_yu. All rights reserved.
//

import UIKit

//extension UIView{
//    func disableAutoResize(){
//        self.setTranslatesAutoresizingMaskIntoConstraints(false)
//    }
//}

class ViewController: UIViewController {

    var lblTitle:UILabel?
    var txtText:UITextField?
    var lblInfo:UILabel?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        _createView()
    }
    
    func _createView(){
        // 创建控件
        lblTitle = addLabel()
        lblTitle?.text = "这是一个测试"
        lblTitle?.font = UIFont.systemFontOfSize(25)
        lblInfo = addLabel()
        lblInfo?.lineBreakMode = NSLineBreakMode.ByWordWrapping
        lblInfo?.numberOfLines = 0
        lblInfo?.font = UIFont.systemFontOfSize(35)
        txtText = UITextField()
        txtText?.setTranslatesAutoresizingMaskIntoConstraints(false)
        txtText?.text = "输入内容"
        txtText?.borderStyle = UITextBorderStyle.RoundedRect
        view.addSubview(txtText!)
        let btnUpdate = UIButton()
        btnUpdate.setTitle("更新", forState: UIControlState.Normal)
        btnUpdate.setTranslatesAutoresizingMaskIntoConstraints(false)
        btnUpdate.backgroundColor  = UIColor.blueColor()
        view.addSubview(btnUpdate)
        btnUpdate.addTarget(self, action: "onUpdate", forControlEvents: UIControlEvents.TouchUpInside)
        
        //设置布局
        var childViews = ["lblTitle":lblTitle!, "lblInfo":lblInfo!, "txtInput":txtText!]
        for (k,v) in childViews{
            setHCenter(k, aView: v, pView: view)
        }
        setHCenter("btnUpdate", aView: btnUpdate, pView: view)
        childViews["btnUpdate"] = btnUpdate
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[lblTitle(==50)]-[txtInput(==30)]-[btnUpdate(==30)]-[lblInfo(>=30)]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: childViews))
        
    }
    
    func addLabel() -> UILabel{
        let label:UILabel = UILabel()
        label.textAlignment = NSTextAlignment.Center
        label.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addSubview(label)
        return label
    }
    
    func setHCenter(key:String,aView:UIView, pView:UIView){
        pView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[\(key)]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: [key:aView]))
    }
    
    func onUpdate(){
        lblInfo?.text = txtText?.text
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

